package cn.damai.mine.collectArraySort;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

public class JsonArraySort {
	
	
	public static JSONArray sortListWithStringKey(List<JSONObject> jsonValues,String sortKey){
		
		JSONArray sortedJsonArray = new JSONArray();
		
		Collections.sort( jsonValues, new Comparator<JSONObject>() {

	        @Override
	        public int compare(JSONObject a, JSONObject b) {
	            String valA = new String();
	            String valB = new String();

	            try {
	                valA = String.valueOf(a.get(sortKey));
	                valB = String.valueOf(b.get(sortKey));
	            } 
	            catch (JSONException e) {
	                //do something
	            }

	            return valA.compareTo(valB);
	        }
	    });

	    for (int i = 0; i < jsonValues.size(); i++) {
	        sortedJsonArray.add(jsonValues.get(i));
	    }
		
	    return sortedJsonArray;
	}
	
	public static JSONArray sortListWithNumKey(List<JSONObject> jsonValues,String sortKey){
		
		JSONArray sortedJsonArray = new JSONArray();
		
		Collections.sort( jsonValues, new Comparator<JSONObject>() {

	        @Override
	        public int compare(JSONObject a, JSONObject b) {
	            Double valA = 0d;
	            Double valB = 0d;

	            try {
	                valA = Double.valueOf(a.getString(sortKey));
	                valB = Double.valueOf(b.getString(sortKey));
	            } 
	            catch (JSONException e) {
	                //do something
	            }

	            return valA.compareTo(valB);
	        }
	    });

	    for (int i = 0; i < jsonValues.size(); i++) {
	        sortedJsonArray.add(jsonValues.get(i));
	    }
		
	    return sortedJsonArray;
	}
	

}
